<template>
  <div class="app-container">
    <div class="map">
      <div class="map-search">
        <!-- <div class="map-search__area">
          <span class="search-title">地区：</span>
          <el-cascader
            v-model="areaValue"
            :options="areaOptions"
            :props="areaProps"
            :teleported="false"
            separator="-"
            placeholder="请选择"
            popper-class="dropDownPanel"
            @change="handleAreaChange"
          />
        </div> -->
      </div>
      <div id="qyContainer" v-loading="loading" element-loading-text="数据更新中" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(25,81,135,0.7)" />
    </div>
    <div class="list">
      <el-alert style="margin-bottom: 10px" title="无人机列表" :closable="false" type="success" />
      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item title="无人机" :name="1">
          <div style="padding-left: 10px">
            <el-collapse v-model="activeNames_" @change="handleChange">
              <el-collapse-item v-for="(item, index) in airList" :key="index" :title="item.department"
                :name="index + 1">
                <div>
                  <div v-for="(v, i) in item.children" :key="i" class="li" @click="handleChange_(v)">
                    <div>{{ v.deviceName }}</div>
                    <el-tag v-if="v.deviceStatus == 1" type="success" size="mini">在线</el-tag>
                    <el-tag v-else type="info" size="mini">离线</el-tag>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
  </div>
</template>
<script>
import {
  uavList
} from '@/api/uavmap'
// 引入地图插件
import AMapLoader from '@amap/amap-jsapi-loader'
// 引入 地址级联选择器和code码转换
import { regionDataPlus } from 'element-china-area-data'
export default {
  name: 'Uavmap',
  data() {
    return {
      airList: [],
      listLoading: true,
      activeNames: 1,
      activeNames_: 0,
      first: true,
      areaProps: {
        // 选择地区的属性
        value: 'value',
        label: 'label',
        children: 'children'
      },
      areaOptions: regionDataPlus, // 地区选择的所有的数据
      areaValue: ['330000', '330100', '330109'], // 地区选择参数，['省区域码', '市区域码']
      loading: false, // 地图是否处于加载中

      map: null, // 当前显示的地图区域对象
      AMap: null, // 拿到的所有的地图的对象

      colorMap: [
        'rgb(255, 0, 13)',
        'rgb(255, 126, 36)',
        'rgb(194, 187, 0)',
        'rgb(26, 255, 0)',
        'rgb(0, 84, 194)'
      ], // 颜色
      markers: [], // 标记
      mapData: [], // 地图上的标记点
      backList: [], // 后端给的所有的数据
      center: [126.578085, 43.859222],
      index: 0,
    }
  },
  mounted() {
    window.closeMarker = this.closeMarker
    window.toMonitoring = this.toMonitoring
    // 设置安全密钥
    window._AMapSecurityConfig = {
      // 必须配合秘钥使用，密钥需要生成，成为开发者之后创建应用即可。
      securityJsCode: 'e5c0fe8d40233deb748b07cfa09ab739'
      // 应用密钥概览：https://console.amap.com/dev/key/app
    }
    this.backList = [] // 假数据，初始化是空数组
    this.mapData = []
    this.markers = [] // 标记
    this.init()
    this.$nextTick(() => {
      this.handleMarker()
    })
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      uavList(this.listQuery).then((response) => {
        this.airList = response
        response.forEach((item, index) => {
          item.children.forEach((v, i) => {
            this.backList.push({
              name: v.deviceName,
              color: 0,
              show: 'none',
              lat: v.position ? v.position.split(',')[1] : '',
              lng: v.position ? v.position.split(',')[0] : '',
              index: this.index
            })
            this.index++;
          })
        })
      })
    },
    init() {
      this.$nextTick(() => {
        AMapLoader.load({
          key: '3bccb9b5337ca1ae0bd58577c6f1ed14',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.LngLat', 'AMap.Marker'],
          AMapUI: {
            version: '1.1',
            plugins: ['overlay/SimpleMarker']
          }
        })
          .then((AMap) => {
            this.AMap = AMap
            this.map = new AMap.Map('qyContainer', {
              viewMode: '2D',
              zoom: 12,
              // mapStyle: "amap://styles/darkblue", // 地图样式，可以自定义
              center: this.center
            })

            // 添加toolbar--放大缩小
            const toolbar = new AMap.ToolBar()
            this.map.addControl(toolbar)
          })
          .catch((e) => {
            console.log(e)
          })
      })
    },
    // 更改地图的地区
    handleAreaChange(e) {
      // ...
    },
    // 处理绘制的点
    handleMarker() {
      this.mapData = this.backList;
      if (this.first) {
        setTimeout(() => {
          this.mapData = this.backList
          // 删除之前的markers
          this.map && this.map.remove(this.markers)
          // 添加markers
          this.addMarkers()
          this.first = false
        }, 1000)
      } else {
        this.mapData = this.backList
        // 删除之前的markers
        this.map && this.map.remove(this.markers)
        // 添加markers
        this.addMarkers()
      }
    },
    handleChange_(e) {
      const lnglat = e.position.split(',');
      this.map.setCenter([lnglat[0], lnglat[1]]);
    },
    // 添加标记点
    addMarkers() {
      const AMap = this.AMap
      if (AMap) {
        this.mapData.forEach((item, index) => {
          const { color } = item
          if (item.lat && item.lng) {
            const obj = {
              position: new AMap.LngLat(item.lng, item.lat),
              zIndex: 98,
              // content: `<span class="circleMark" style='background:${this.colorMap[color]}'></span>`,
              content: `<div class="circleMark"></div>`,
              offset: new this.AMap.Pixel(-20, -40)
            }
            const marker = new AMap.Marker(obj)
            const marker2 = new AMap.Marker({
              position: new AMap.LngLat(item.lng, item.lat),
              // content: `<span class="circleMark" style='background:${this.colorMap[color]}'>1151651</span>`,
              content: `<div class="circleMarkInfo" style="display:${item.show}">
                            <div class="title">${item.name}<div class="close" onclick="closeMarker(${index})">×</div></div>
                            <div class="list">
                              <div class="text">任务名称：城市巡检任务</div>
                              <div class="text">执行航线：航线</div>
                              <div class="text">航线类型：定点航向</div>
                              <div class="text">航线里程：7km</div>
                              <div class="text">执行时间：2024-10-29 10:00:00</div>
                              <div class="text">
                                当前进度：
                                <div class="plan"><div class="now">70%</div></div>
                              </div>
                            </div>
                            <div class="btn" onclick="toMonitoring('${item.name}')">实时视频<div>
                        </div>`,
              zIndex: 99,
              offset: new this.AMap.Pixel(-125, -310),
              active: false,
              extData: {
                hasEffect: color === 2 // 是否需要涟漪效果
              }
            })
            // 绑定事件
            marker.on('click', this.clickMarkerHandler.bind(this, item))
            // 将创建的点标记添加到已有的地图实例：
            this.map.add([marker2, marker])
            if (marker2._opts.extData.hasEffect) {
              marker2.dom.classList.add('rippleEffect') // 添加涟漪样式
            }
            this.markers.push(marker2, marker)
          }
        })
      }
    },
    // 点击marker触发事件
    clickMarkerHandler(item, event) {
      console.log(item, 888)
      if (this.backList[item.index].show === 'none') {
        this.backList[item.index].show = 'block'
      } else {
        this.backList[item.index].show = 'none'
      }
      this.handleMarker()
    },
    closeMarker(index) {
      if (this.backList[index].show === 'block') {
        this.backList[index].show = 'none'
        this.handleMarker()
      }
    },
    toMonitoring(item) {
      this.$router.push({ path: '/monitoring/detail' })
    },
    handleChange() { }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;

  .map {
    position: relative;

    .map-search {
      position: absolute;
      z-index: 10;
    }

    #qyContainer {
      padding: 0px;
      margin: 0px;
      width: 100%;
      height: calc(100vh - 85px);
    }

    ::v-deep .circleMark {
      display: inline-block;
      width: 40px;
      height: 40px;
      background-image: url("../../assets/images/air.png");
      background-size: 100% 100%;
    }

    ::v-deep .circleMarkInfo {
      width: 250px;
      background-color: #fff;
      border-radius: 10px;
      overflow: hidden;
      position: relative;
      box-shadow: 0px 10px 30px 0px rgba(101, 101, 101, 0.5);

      .title {
        background-color: #409EFF;
        text-align: center;
        line-height: 28px;
        color: #fff;
        font-size: 14px;
        margin-bottom: 6px;
        position: relative;

        .close {
          position: absolute;
          height: 28px;
          width: 28px;
          line-height: 28px;
          text-align: center;
          font-size: 24px;
          color: #fff;
          top: 0;
          right: 0;
        }
      }

      .list {
        padding: 14px;
      }

      .text {
        font-size: 12px;
        color: #333;
        line-height: 26px;
        display: flex;
        align-items: center;

        .plan {
          width: 160px;
          height: 12px;
          border-radius: 6px;
          background-color: rgb(235, 238, 245);

          .now {
            width: 70%;
            height: 100%;
            background-color: #409EFF;
            color: #fff;
            border-radius: 6px;
            font-size: 10px;
            line-height: 12px;
            text-align: right;
            padding-right: 8px;
          }
        }
      }

      .btn {
        padding: 4px 0;
        border: 1px solid #eee;
        border-radius: 5px;
        font-size: 13px;
        color: rgb(64, 158, 255);
        width: 80px;
        text-align: center;
        margin: 0 auto 15px;
      }
    }

    ::v-deep .rippleEffect {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      // animation: amapTransition 2s linear infinite;
    }

    @keyframes amapTransition {
      0% {
        -webkit-transform: scale(1);
        -moz-transform: scale(1);
        -o-transform: scale(1);
        transform: scale(1);
        opacity: 1;
      }

      100% {
        -webkit-transform: scale(3);
        -moz-transform: scale(3);
        -o-transform: scale(3);
        transform: scale(3);
        opacity: 0.5;
      }
    }
  }

  .list {
    position: absolute;
    width: 240px;
    left: 20px;
    top: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 10px 30px 0px rgba(101, 101, 101, 0.5);

    .li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 30px;
      cursor: pointer;
      padding: 0 10px;
      border-radius: 6px;

      &:hover {
        background-color: rgba($color: #409eff, $alpha: 0.2);
      }
    }
  }
}
</style>
